//
//  SRBatteryService.m
//  SportRing
//
//  Created by mykoma on 14/10/28.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRBatteryService.h"
#import "BlueToothLib.h"
#import "SRDB.h"

@implementation SRBatteryService

+ (void)addObserverForBleData
{
    [[NSNotificationCenter defaultCenter] addObserverForName:NOTIFY_GET_BATTERY
                                                      object:nil
                                                       queue:nil
                                                  usingBlock:^(NSNotification *note)
     {
         NSData * nsdata = (NSData *)note.object;
         const void * data = nsdata.bytes;
         
         uint8_t battery;
         memcpy(&battery, &data[0], 1);
         SRDevice * device = [SRDevice findDeviceForMe:[SRMe currentUser]];
         [device configAttributesWithBlock:^(SRDevice *deviceSelf) {
             deviceSelf.battery = @(battery);
         }];
     }];
}

+ (RACSignal *)readBatteryFromDevice
{
    static id batteryObserver = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:batteryObserver];
    
    RACSubject * subject = [RACSubject subject];
    
    batteryObserver = [[NSNotificationCenter defaultCenter] addObserverForName:NOTIFY_RECIVED_BATTERY
                                                                        object:nil
                                                                         queue:nil
                                                                    usingBlock:^(NSNotification *note)
                       {
                           [subject sendNext:nil];
                       }];
    
    [BlueToothLib getBatteryWithBlock:^(BOOL isTimeOut) {
        if (isTimeOut) {
            [subject sendNext:nil];
        }
    }];
    return subject;
}

@end
